<template>
  <view class="complete-desc-component">
    <!-- 完成工单描述弹窗 -->
    <uni-popup ref="completeDescPopup" type="center">
      <view class="complete-desc-popup-content">
        <text class="complete-desc-popup-title">完成工单描述</text>
        <textarea class="complete-desc-input" v-model="completeDesc" placeholder="请输入完成工单的描述内容"
          maxlength="400"></textarea>
        <view class="complete-desc-popup-btn-group">
          <button class="complete-desc-popup-cancel-btn" @click="closeCompleteDescPopup">取消</button>
          <button class="complete-desc-popup-confirm-btn" @click="confirmDesc">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { uploadImage, completeTicket } from '../life/repairDetail/repairDetail.js';

export default {
  props: {
    // 工单编号
    orderNumber: {
      type: String,
      required: true
    },
    // 工单ID
    orderId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      completeDesc: '' // 完成工单描述内容
    };
  },
  // 合并所有方法到一个methods对象中
  methods: {
    // 打开弹窗（统一方法名，避免混淆）
    openCompleteDescPopup() {
      this.$refs.completeDescPopup.open();
    },

    // 关闭弹窗
    closeCompleteDescPopup() {
      this.$refs.completeDescPopup.close();
      this.completeDesc = '';
    },

    // 确认描述（模板中绑定的方法，必须存在）
    confirmDesc() {
      if (!this.completeDesc.trim()) {
        uni.showToast({
          title: '请输入完成工单描述',
          icon: 'none'
        });
        return;
      }

      // 调用拍照函数
      this.takePhoto(this.completeDesc);
      this.closeCompleteDescPopup();
    },

    // 拍照并上传
    takePhoto(completeDesc) {
      uni.authorize({
        scope: 'scope.camera',
        success: () => this._chooseImage(completeDesc),
        fail: () => {
          uni.showModal({
            title: '权限申请',
            content: '需要相机权限才能拍照，请在设置中开启',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.camera'])
                      this._chooseImage(completeDesc);
                  }
                });
              }
            }
          });
        }
      });
    },

    // 拍照核心逻辑
    async _chooseImage(completeDesc) {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: async (photoRes) => {
          const tempImagePath = photoRes.tempFilePaths[0];
          try {
            uni.showLoading({
              title: '上传图片中...'
            });
            // 上传图片并获取后端返回的完成图片路径
            const resimage = await uploadImage(tempImagePath);
            const finishPicture = resimage.data.signatureImage; // 后端返回的单张完成图片路径
            
            // 调用完成工单接口
            const res = await completeTicket(this.orderNumber, [finishPicture], completeDesc);
            
            // 通知父组件完成工单成功
            this.$emit('orderCompleted', {
              success: true,
              data: res.data,
              completeDesc: completeDesc,
              finishPicture: finishPicture
            });
            
            uni.showToast({
              title: '工单已完成',
              icon: 'success'
            });
          } catch (err) {
            console.error('图片上传失败:', err);
            this.$emit('orderCompleted', {
              success: false,
              error: err
            });
            uni.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          } finally {
            uni.hideLoading();
          }
        },
        fail: (err) => {
          if (err.errMsg !== 'chooseImage:fail cancel') {
            this.$emit('orderCompleted', {
              success: false,
              error: err
            });
            uni.showToast({
              title: '拍照失败，请重试',
              icon: 'none'
            });
          }
        }
      });
    }
  }
};
</script>

<style>
.complete-desc-popup-content {
  width: 70vw;
  background-color: #fff;
  border-radius: 16px;
  padding: 16px;
  box-sizing: border-box;
  margin: auto;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.complete-desc-popup-title {
  display: flex;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 16px;
}

.complete-desc-input {
  width: 100%;
  min-height: 80px;
  padding: 10px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  box-sizing: border-box;
  resize: none;
  margin-bottom: 16px;
}

.complete-desc-popup-btn-group {
  display: flex;
  justify-content: space-between;
  gap: 12px;
}

.complete-desc-popup-cancel-btn,
.complete-desc-popup-confirm-btn {
  flex: 1;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 24px;
  font-size: 15px;
  transition: all 0.3s ease;
}

.complete-desc-popup-cancel-btn {
  background-color: #f8f8f8;
  color: #999;
  border: 1px solid #e5e5e5;
}

.complete-desc-popup-cancel-btn:active {
  background-color: #f0f0f0;
}

.complete-desc-popup-confirm-btn {
  background-color: #1677ff;
  color: #fff;
  border: none;
}

.complete-desc-popup-confirm-btn:active {
  background-color: #0958d9;
}
</style>